<template>
  <div>
    <div class="header-container">
      <h1>账户信息</h1>
      <TabItem
        :tabs="tabs"
        :active-index="activeIndex"
        @handleClick="handleClick"
      />
    </div>
    <div class="middle-container" />
    <div class="main-container">
      <div v-if="activeIndex === 0">
        <!-- 企业信息 -->
        <Company v-if="companyFlag" :disabled-save="disabledSave" @editPhone="editPhone" @saveNick="saveNick" />
        <!-- 个人信息 -->
        <Personal v-else ref="personal" :disabled-save="disabledSave" @editPhone="editPhone" @saveNick="saveNick" />
      </div>
      <div v-else>
        <!-- 头像信息 -->
        <HeadPortrait />
      </div>
    </div>
    <!-- 弹窗1 -->
    <div v-if="showPopUpOne" class="pop-up">
      <div class="add-container in-edit">
        <div class="txt">
          <div>修改手机号码</div>
          <span
            class="el-icon-close"
            @click="closePopUp('formLabelAlignOne')"
          />
        </div>
        <div class="add-content">
          <el-form
            ref="formLabelAlignOne"
            label-width="150px"
            :model="formLabelAlignOne"
          >
            <el-form-item
              label="你正在更改手机号："
              class="now-edit"
              prop="phone"
            >
              <el-input :value="formLabelAlignOne.phone | userNickFormat" />
            </el-form-item>
            <el-form-item
              label="请填写手机验证码："
              class="phone-code"
              prop="securityCode"
            >
              <el-input v-model="formLabelAlignOne.securityCode" />
              <span
                class="verification-code"
                :disabled="!phoneStepOne.canSend"
                @click="getVerificationCode(true)"
                v-text="phoneStepOne.content"
              >获取验证码</span>
            </el-form-item>
            <el-form-item label="">
              <div class="confirm-btn" @click="next">下一步</div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <!-- 弹窗2 -->
    <div v-if="showPopUp" class="pop-up">
      <div class="add-container">
        <div class="txt">
          <div>修改手机号码</div>
          <span class="el-icon-close" @click="closePopUp('formLabelAlign')" />
        </div>
        <div class="add-content">
          <el-form
            ref="formLabelAlign"
            label-width="150px"
            :model="formLabelAlign"
          >
            <el-form-item label="请输入新手机号码：" prop="phone">
              <el-input v-model="formLabelAlign.phone" />
            </el-form-item>
            <el-form-item
              label="请填写手机验证码："
              class="phone-code"
              prop="securityCode"
            >
              <el-input v-model="formLabelAlign.securityCode" />
              <span
                class="verification-code"
                :disabled="!phoneStepTwo.canSend"
                @click="getVerificationCode(false)"
                v-text="phoneStepTwo.content"
              >获取验证码</span>
            </el-form-item>
            <el-form-item label="">
              <div class="confirm-btn" @click="confirm">确认</div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TabItem from '@/components/Tab'
import Personal from './component/Personal'
import HeadPortrait from './component/HeadPortrait'
import Company from './component/Company'
import { captcha } from '@/api/common'
import { countdown } from '@/util/countdown'
import { changeUserNick } from '@/api/personal-center'
import {
  phoneReg,
  phoneCodeReg,
  charReg,
  Chinese,
  emojiReg,
  FullWidth,
  HalfWidth,
  ToCDB
} from '@/js/regex'
import {
  beforeChangePhone,
  beforeChangePhoneCheck,
  checkUserPhone,
  mobileChange,
  changePhone
} from '@/api/personal-center'
export default {
  components: {
    TabItem,
    Personal,
    HeadPortrait,
    Company
  },
  data() {
    return {
      tabs: ['个人信息', '头像信息'],
      activeIndex: 0,
      companyFlag: this.$store.getters.companyFlag,
      disabledSave: false,
      showPopUp: false,
      showPopUpOne: false,
      // 这俩是图形验证码相关的
      uuid: '',
      code: '',
      // 弹窗1
      formLabelAlignOne: {
        phone: '',
        securityCode: ''
      },
      phoneStepOne: {
        content: '获取验证码', // 按钮里显示的内容
        totalTime: 60,
        canSend: true,
        send: false,
        clock: undefined,
        disabled: false,
        uuid: ''
      },
      // 弹窗2
      formLabelAlign: {
        phone: '',
        securityCode: '',
        uuid: ''
      },
      phoneStepTwo: {
        content: '获取验证码', // 按钮里显示的内容
        totalTime: 60,
        canSend: true,
        send: false,
        clock: undefined,
        disabled: false,
        uuid: ''
      }
    }
  },
  mounted() {
    this.handleClick(this.activeIndex)
    this.tabs.splice(0, 1, this.companyFlag ? '企业信息' : '个人信息')
  },
  methods: {
    handleClick(index) {
      this.activeIndex = index
    },
    saveNick(userNick) {
      if (!userNick) {
        this.$message('昵称不能为空')
        return
      }
      if (userNick && userNick.length > 12) {
        this.$message('昵称不能不得超过十二位')
        return
      }
      // 半角非法字符
      if (charReg.test(userNick)) {
        this.$message('昵称不能含有非法字符')
        return
      }
      // 过滤掉emoji表情代码
      if (emojiReg.test(userNick)) {
        this.$message('昵称暂不支持emoji表情')
        return
      }
      // 先去掉汉字和半角字符,再去匹配全角字符
      const str = userNick
        .replace(Chinese, '')
        .replace(HalfWidth, '')
        .match(FullWidth)
      if (str && str.length) {
        // 全角转半角,再匹配一次非法字符
        if (charReg.test(ToCDB(str.join('')))) {
          this.$message('昵称不能含有非法字符')
          return
        }
      }
      this.disabledSave = true
      changeUserNick(userNick)
        .then(res => {
          if (res.data) {
            this.$store.dispatch('setName', userNick)
            const userInfo = JSON.parse(
              JSON.stringify(this.$store.getters.info)
            )
            userInfo.userNick = userNick
            this.$store.dispatch('setInfoParam', userInfo)
            this.disabledSave = false
            this.$message('昵称修改成功')
          } else {
            this.disabledSave = false
            this.$message('昵称修改失败,请稍后再试')
          }
        })
        .catch(() => {
          this.disabledSave = false
          this.$message('昵称修改失败,请稍后再试')
        })
    },
    async validUserPhone(userPhone) {
      if (!userPhone) {
        this.$message('请先填写手机号')
        return false
      }
      if (!phoneReg.test(userPhone)) {
        this.$message('手机号格式不正确')
        return false
      }
      const res = await checkUserPhone(userPhone)
      if (!res.data) {
        this.$message(`手机号 "${userPhone}" 已被占用`)
        return false
      }
      return true
    },
    next() {
      if (!this.phoneStepOne.send) {
        this.$message('请先获取验证码')
        return
      }
      if (!this.formLabelAlignOne.securityCode) {
        this.$message('请先输入验证码')
        return
      }
      if (!phoneCodeReg.test(this.formLabelAlignOne.securityCode)) {
        this.$message('验证码只能为六位纯数字')
        return
      }
      this.phoneStepOne.disabled = true
      const headers = {
        uuid: this.phoneStepOne.uuid
      }
      beforeChangePhoneCheck(headers, this.formLabelAlignOne.securityCode)
        .then(res => {
          if (res.data) {
            this.showPopUpOne = false
            this.showPopUp = true
            this.formLabelAlign.securityCode = ''
            this.phoneStepTwo.uuid = res.message
          } else {
            this.phoneStepOne.disabled = false
            this.$message('验证码错误')
          }
        })
        .catch(() => {
          this.phoneStepOne.disabled = false
        })
    },
    async confirm() {
      if (await this.validUserPhone(this.formLabelAlign.phone)) {
        if (!this.phoneStepTwo.send) {
          this.$message('请先获取验证码')
          return
        }
        if (!this.formLabelAlign.securityCode) {
          this.$message('请先填写验证码')
          return
        }
        if (!phoneCodeReg.test(this.formLabelAlign.securityCode)) {
          this.$message('验证码只能为六位纯数字')
          return
        }
        const headers = {
          uuid: this.formLabelAlign.uuid,
          mobile: this.formLabelAlign.phone
        }
        changePhone(headers, this.formLabelAlign.securityCode).then(res => {
          if (res.data) {
            const userInfo = JSON.parse(JSON.stringify(this.$store.getters.info))
            if (this.companyFlag) {
              userInfo.userPhone = this.formLabelAlign.phone
              this.$refs.company.form.phone = this.formLabelAlign.phone
            } else {
              userInfo.userName = this.formLabelAlign.phone
              this.$refs.personal.form.phone = this.formLabelAlign.phone
            }
            this.$store.dispatch('setInfoParam', userInfo)
            this.showPopUp = false
            document.body.style.overflow = 'auto'
            this.$message('修改成功')
          } else {
            this.$message('修改失败')
          }
        })
      }
    },
    editPhone(phone) {
      document.body.style.overflow = 'hidden'
      this.showPopUpOne = true
      this.formLabelAlignOne.phone = phone
      this.formLabelAlignOne.securityCode = ''
    },
    closePopUp(form) {
      this.$refs[form].resetFields()
      this.showPopUp = false
      this.showPopUpOne = false
      document.body.style.overflow = 'auto'
    },
    async getVerificationCode(flag) {
      if (flag) {
        // 解绑旧手机号
        captcha().then(response => {
          this.uuid = response.message
          this.code = response.data
          if (!this.phoneStepOne.canSend) {
            return
          }
          countdown(this.phoneStepOne)
          beforeChangePhone({
            uuid: this.uuid,
            code: this.code
          }).then(res => {
            if (res.data) {
              this.phoneStepOne.send = true
              this.phoneStepOne.uuid = res.message
            } else {
              this.$message('发送失败,请稍后重试')
              this.phoneStepOne.send = false
              window.clearInterval(this.phoneStepOne.clock)
              this.phoneStepOne.content = '重发验证码'
              this.phoneStepOne.totalTime = 60
              this.phoneStepOne.canSend = true
            }
          }).catch(res => {
            this.$message(res.data)
            this.phoneStepOne.send = false
            window.clearInterval(this.phoneStepOne.clock)
            this.phoneStepOne.content = '重发验证码'
            this.phoneStepOne.totalTime = 60
            this.phoneStepOne.canSend = true
          })
        })
      } else {
        // 验证码新手机号
        if (await this.validUserPhone(this.formLabelAlign.phone)) {
          if (!this.phoneStepTwo.canSend) {
            return
          }
          countdown(this.phoneStepTwo)
          const headers = {
            uuid: this.phoneStepTwo.uuid,
            mobile: this.formLabelAlign.phone
          }
          mobileChange(headers, this.formLabelAlignOne.securityCode).then(
            res => {
              if (res.data) {
                this.phoneStepTwo.send = true
                this.formLabelAlign.uuid = res.message
              } else {
                this.$message('发送失败,请稍后重试')
                this.phoneStepTwo.send = false
                window.clearInterval(this.phoneStepTwo.clock)
                this.phoneStepTwo.content = '重发验证码'
                this.phoneStepTwo.totalTime = 60
                this.phoneStepTwo.canSend = true
              }
            }
          )
        }
      }
    },
    selectItem(item) {
      this.value = item
    }

  }
}
</script>

<style scoped lang="scss">
.in-edit {
  .now-edit {
    ::v-deep .el-input__inner {
      border: none;
      outline: none;
    }
  }
}
::v-deep .el-button--primary {
  color: #02a9f1ff;
  // background-color: #409EFF;
  // border-color: #409EFF;
  background-color: #fff;
  border: none;
  height: 35px;
}
.header-container {
  height: 57px;
  background-color: #fff;
  padding: 18px 20px 18px 30px;
  display: flex;
  // justify-content: space-between;
  align-items: center;
  // margin-bottom: 20px;
  h1 {
    font-weight: 700;
    font-size: 16px;
  }
}
.middle-container {
  height: 20px;
  background-color: #f7f7f7;
}
.main-container {
  padding: 15px 20px 20px 20px;
  background-color: #fff;

  .btn {
    background-color: #ff3b30;
    width: 110px;
    height: 37px;
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
.pop-up {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  .add-container {
    width: 538px;
    .txt {
      color: #3d3d3d;
      font-size: 16px;
      border: 1px solid #e5e5e5;
      height: 42px;
      background-color: #e5e5e5;
      display: flex;
      padding: 0 15px 0 21px;
      justify-content: space-between;
      align-items: center;
      .el-icon-close {
        font-weight: 700;
      }
      .el-icon-close:hover {
        cursor: pointer;
      }
    }
    .add-content {
      background-color: #fff;
      height: 300px;
      width: 100%;
      position: relative;
      padding: 50px 0 98px 44px;
      ::v-deep & .el-input__inner {
        width: 180px;
      }
      ::v-deep .el-input {
        width: 180px;
        height: 35px;
      }
      .verification-code {
        display: inline-block;
        width: 106px;
        height: 32px;
        background-color: #f5f5f5;
        color: #8d8d8d;
        border: 1px solid #e5e5e5;
        border-radius: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 3px;
        right: 50px;
      }
      .confirm-btn {
        width: 110px;
        height: 37px;
        border-radius: 5px;
        background-color: #ff3b30;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
      }
      .confirm-btn:hover {
        cursor: pointer;
      }
    }
  }
}
::v-deep .el-form-item__label {
  padding-right: 15px;
  height: 35px;
}
::v-deep .el-form-item {
  margin-bottom: 13px;
}
::v-deep .el-input {
  height: 35px;
  width: 270px;
}
::v-deep .el-input__inner {
  height: 35px;
  width: 270px;
}
::v-deep .el-form-item__content {
  height: 35px;
}
::v-deep .el-select {
  height: 35px;
  .el-input--suffix {
    height: 35px;
  }
}
::v-deep .el-icon-arrow-up:before {
  content: "\e6e1";
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #f8f8f8;
}
::v-deep .avatar-uploader {
  width: 251px;
  height: 251px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 251px;
  height: 251px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-icon-plus:before {
  content: "";
}
::v-deep .el-upload {
  width: 251px;
  height: 251px;
  .avatar {
    width: 251px;
    height: 251px;
  }
}
</style>
